package com.chb.utils;

import com.chb.entity.SecurityUserInfo;
import com.chb.properties.SecurityConfigProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * @description:
 * @author: CHB
 * @create: 2021-11-23 17:43
 **/
@Slf4j
@Component
public class JwtUtils {

    private static final String USER_NAME = "name";
    @Resource
    private SecurityConfigProperties securityConfigProperties;
    /**
     * 获取负载
     * @param token
     * @return
     */
    public  Claims getClaims(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(securityConfigProperties.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.info("token parser error");
        }
        return claims;
    }

    /**
     * 生成token
     * @param user
     * @return
     */
    public String generateToken(SecurityUserInfo user){
        HashMap<String, Object> claims = new HashMap<>(2);
        claims.put(USER_NAME,user.getName());
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + securityConfigProperties.getJwtExpiration() * 1000))
                .signWith(SignatureAlgorithm.HS512, securityConfigProperties.getJwtSecret())
                .compact();
    }
}

